import os

import pyecharts.options as opts
from pyecharts.charts import Bar, Timeline
from pyecharts.globals import ThemeType

# 数据目录
data_dir = "/root/eduhq/result/ads_user_region"
# 背景图片地址
background_image_path = "/root/eduhq/images/img_2.png"
# 图表存放地址
output_dir = "/root/eduhq/html"


# 读取数据
def read_data():
    quarters = []
    regions = set()
    data = {}

    for filename in os.listdir(data_dir):
        if filename.endswith('.txt'):
            quarter = filename.split('.')[0]
            quarters.append(quarter)
            with open(os.path.join(data_dir, filename), 'r') as file:
                lines = file.readlines()
                data[quarter] = [int(line.strip()) for line in lines]
                regions.update([f"地区{i + 1}" for i in range(len(lines))])

    return quarters, list(regions), data


# 读取数据
quarters, regions, data = read_data()

# 创建时间轴
timeline = Timeline()

# 绘制柱状图并添加到时间轴
for quarter in quarters:
    bar = (
        Bar(init_opts=opts.InitOpts(theme=ThemeType.LIGHT, width='1200px', height='600px'))
        .add_xaxis(regions)
        .add_yaxis(quarter, data[quarter])
        .set_global_opts(
            title_opts=opts.TitleOpts(title="不同经济大区用户访问量统计柱形图"),
            xaxis_opts=opts.AxisOpts(name="经济大区"),
            yaxis_opts=opts.AxisOpts(name="访问量"),
            background_color_opts=opts.BackgroundColorOpts(image=background_image_path),
        )
    )
    timeline.add(bar, time_point_name=quarter)

# 设置时间轴播放动画等参数
timeline.add_schema(
    is_auto_play=True,
    play_interval=2000,  # 播放间隔时间（毫秒）
    is_loop_play=True  # 是否循环播放
)

# 渲染图表
output_file = os.path.join(output_dir, "不同经济大区用户访问量统计柱形图.html")
timeline.render(output_file)
